import { operationType } from '../../types';
import CheckboxControlService from '../checkbox/service';

class OperationService extends CheckboxControlService {

  onChange(value: string[]) {
    this.value = value;
    this.updateProperties(value);
  }

  updateProperties(value: string[]) {
    const element = this.panel.getElement();
    const moddle = this.root.getModdle();

    const oldExtensionElements = element.businessObject.extensionElements;
    const oldConfig = oldExtensionElements?.values?.filter((it: any) => it.$type !== `flowable:buttons`) || [];

    const values = value.join(',');

    const extensionElements = moddle.create(
      'bpmn:ExtensionElements',
      {
        values: [
          ...oldConfig,
          moddle.create(
            `flowable:buttons`,
            {
              value: values
            },
          ),
        ],
      },
    );

    this.root.getModeling().updateProperties(
      element,
      {
        extensionElements
      },
    );
  }

  init() {
    const element = this.panel.getElement();
    const extensionElements = element.businessObject.extensionElements;
    const dom = extensionElements?.values?.find((e: any) => e.$type === `flowable:buttons`);
    if(dom){
      const ids: string = dom?.value || '';
      if (ids) {
        this.value = ids.split(',');
      } else {
        this.value = [];
      }
    }else{
      // 触发一次onChange，将默认值写入
      this.onChange([
        operationType.agree,
        operationType.turnInto,
        operationType.reject,
      ]);
    }
  }

}

export default OperationService;
